import { Modal, Radio, Form, Input, Button, Checkbox, Row, Col, message } from 'antd';
import { useEffect, useState } from 'react';
import { getCaptcha, userIsExist, addUser } from '../api/user';
import styles from '../css/LoginForm.module.css';
import { useDispatch } from 'react-redux';
import { initUserInfo, changeLoginStatus } from '../redux/userSlice';

function LoginForm(props) {
  const [value, setValue] = useState(1);

  const dispatch = useDispatch();

  // 登录表单
  const [loginInfo, setLoginInfo] = useState({
    loginId: '',
    password: '',
    remember: false,
  });

  // 注册表单的状态数据
  const [registerInfo, setRegisterInfo] = useState({
    loginId: '',
    nickname: '',
    captcha: '',
  });

  const [captcha, setCaptcha] = useState(null);

  useEffect(() => {
    // alert('isShow changed');
    captchaClickHandle();
  }, [props.isShow]);

  const onChange = (e) => {
    setValue(e.target.value);
    captchaClickHandle();
  };

  function loginHandle() {
    alert(1);
  }

  function handleCancel() {
    props.closeModal();
  }

  /**
   * 验证登录账号是否存在
   */
  async function checkLoginIdIsExist() {
    if (registerInfo.loginId) {
      const { data } = await userIsExist(registerInfo.loginId);
      if (data) {
        // 该 loginId 已经注册过了
        return Promise.reject('该用户已经注册过了');
      }
    }
  }

  async function registerHandle() {
    // const result = await userIsExist(registerInfo.loginId);
    const result = await addUser(registerInfo);
    console.log(result);
    if (result.data) {
      message.success('注册成功');
      dispatch(initUserInfo(result.data));
      dispatch(changeLoginStatus(true));
      // 关闭登录注册的弹出框
      handleCancel();
    } else {
      message.warning('注册失败');
      captchaClickHandle();
    }
  }

  const updateInfo = (target, value, field, setHandler) => {
    const obj = { ...target };
    obj[field] = value;
    setHandler(obj);
  };

  async function captchaClickHandle() {
    const result = await getCaptcha();
    setCaptcha(result);
    // console.log(result);
  }

  // captchaClickHandle();

  let container;
  if (value === 1) {
    container = (
      <div className="">
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          onFinish={loginHandle}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="账号"
            name="loginId"
            rules={[{ required: true, message: '请输入账号' }]}
          >
            <Input
              value={loginInfo.loginId}
              placeholder="请输入账号"
              onChange={(e) => updateInfo(loginInfo, e.target.value, 'loginId', setLoginInfo)}
            />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              value={loginInfo.password}
              placeholder="请输入密码"
              onChange={(e) => updateInfo(loginInfo, e.target.value, 'password', setLoginInfo)}
            />
          </Form.Item>

          <Form.Item
            label="验证码"
            name="captcha"
            rules={[{ required: true, message: '请输入验证码' }]}
          >
            <Row>
              <Col span={16}>
                <Input
                  value={loginInfo.captcha}
                  placeholder="请输入验证码"
                  onChange={(e) => updateInfo(loginInfo, e.target.value, 'captcha', setLoginInfo)}
                />
              </Col>
              <Col span={6}>
                <div
                  className={styles.captchaImg}
                  onClick={captchaClickHandle}
                  dangerouslySetInnerHTML={{ __html: captcha }}
                ></div>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item name="remember" wrapperCol={{ offset: 4, span: 16 }}>
            <Checkbox
              checked={loginInfo.remember}
              onChange={(e) => updateInfo(loginInfo, e.target.checked, 'remember', setLoginInfo)}
            >
              记住密码
            </Checkbox>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
            <div className="flex gap-2">
              <Button type="primary" htmlType="submit">
                登录
              </Button>
              <Button type="default" htmlType="submit">
                重置
              </Button>
            </div>
          </Form.Item>
        </Form>
      </div>
    );
  } else {
    container = (
      <div className="">
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          onFinish={registerHandle}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="账号"
            name="loginId"
            rules={[{ required: true, message: '请输入账号' }, { validator: checkLoginIdIsExist }]}
          >
            <Input
              value={registerInfo.loginId}
              placeholder="请输入账号"
              onChange={(e) => updateInfo(registerInfo, e.target.value, 'loginId', setRegisterInfo)}
            />
          </Form.Item>
          <Form.Item
            label="昵称"
            name="nickname"
            rules={[{ required: true, message: '请输入昵称' }]}
          >
            <Input
              value={registerInfo.loginId}
              placeholder="请输入昵称"
              onChange={(e) =>
                updateInfo(registerInfo, e.target.value, 'nickname', setRegisterInfo)
              }
            />
          </Form.Item>

          <Form.Item
            label="验证码"
            name="captcha"
            rules={[{ required: true, message: '请输入验证码' }]}
          >
            <Row>
              <Col span={16}>
                <Input
                  value={registerInfo.captcha}
                  placeholder="请输入验证码"
                  onChange={(e) =>
                    updateInfo(registerInfo, e.target.value, 'captcha', setRegisterInfo)
                  }
                />
              </Col>
              <Col span={6}>
                <div
                  className={styles.captchaImg}
                  onClick={captchaClickHandle}
                  dangerouslySetInnerHTML={{ __html: captcha }}
                ></div>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
            <div className="flex gap-2">
              <Button type="primary" htmlType="submit">
                注册
              </Button>
              <Button type="default" htmlType="submit">
                重置
              </Button>
            </div>
          </Form.Item>
        </Form>
      </div>
    );
  }
  return (
    <div>
      <Modal title="注册/登录" open={props.isShow} onCancel={props.closeModal}>
        <Radio.Group
          optionType="button"
          buttonStyle="solid"
          className="w-full flex text-center"
          value={value}
          onChange={onChange}
        >
          <Radio.Button className="basis-1/2" value={1}>
            登录
          </Radio.Button>
          <Radio.Button className="basis-1/2" value={2}>
            注册
          </Radio.Button>
        </Radio.Group>
        <div className="pt-6">{container}</div>
      </Modal>
    </div>
  );
}

export default LoginForm;
